package service;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.MessageDao;
import entry.Message;
import entry.User;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.IOException;
import java.util.List;

@WebServlet("/message")
public class MessageList extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    MessageDao messageDao = new MessageDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 得到当前用户的id
        HttpSession session = req.getSession(false);
        User user  = (User)session.getAttribute("user");
        int userId = user.getUserId();
        String talkIdStr = req.getParameter("authorId");
        int talkId = 0;
        if (talkIdStr != null){
            // 得到会话窗口的 id
            talkId = Integer.parseInt(req.getParameter("authorId"));
        }
        String list = req.getParameter("list");

        // 返回消息列表
        if (list != null && list.equals("yes")){
            resp.setContentType("application/json; charset=utf8");
            List<User> talkers = messageDao.findTalker(userId);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(objectMapper.writeValueAsString(talkers));
            return;
        }

        List<Message> messages = messageDao.getMessagesById(userId, talkId);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(objectMapper.writeValueAsString(messages));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 得到当前用户的id
        HttpSession session = req.getSession(false);
        User user  = (User)session.getAttribute("user");
        int userId = user.getUserId();
        // 得到会话窗口的id
        int talkId = Integer.parseInt(req.getParameter("authorId"));

        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        message.setFrom(userId);
        message.setTo(talkId);
        messageDao.insertMessage(message);

        resp.getWriter().write("success");
    }
}
